<?php

namespace App\Http\Controllers\v1;


use App\Models\Area;
use App\Models\DuiBa;
use App\Models\Family;
use App\Models\Org;
use App\Models\Project;
use App\Models\SmsCode;
use App\Models\Team;
use App\Models\User;
use App\Models\UserCollection;
use App\Models\UserMessage;
use App\Models\UserTeam;
use App\Models\Volunteer;
use App\Models\VolunteerGoodAt;
use EasyWeChat\Core\Exception;
use Illuminate\Http\Request;
use App\Libs\IdCard;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use Hashids\Hashids;
use anlutro\LaravelSettings\Facade AS Setting;

class DuiBaController extends Controller
{

    public  function buy(Request $request)
    {
        $userId = $request->get('uid');

        $userInfo = User::findorfail($userId);
        $orgInfo = Org::where('id', $userInfo->org_id)->first();

        if($orgInfo->duiba_key != $request->get('appKey'))
        {
            $data = [

                'status' => 'fail',
                'errorMessage' => '用户信息错误，请联系管理员',
                'credits' => $userInfo->volunteer->score,
            ];
            return $data;
        }

        try
        {
            $credit = parseCreditConsume($orgInfo->duiba_key, $orgInfo->duiba_secret, $request->input());
        }catch (\Exception $e)
        {
            $data = [

                'status' => 'fail',
                'errorMessage' => $e->getMessage(),
                'credits' => $userInfo->volunteer->score,
            ];
            return $data;
        }

        if($userInfo->volunteer->score < $credit['credits'])
        {
            $data = [

                'status' => 'fail',
                'errorMessage' => '积分不足',
                'credits' => $userInfo->volunteer->score,
            ];
            return $data;
        }

        DB::beginTransaction();
        try{
            $userInfo->volunteer->decrement('score', $credit['credits']);
            $duiba = new DuiBa();
            $duiba->fill(
                [
                    'user_id'=>$userInfo->id,
                    'score'=>$credit['credits'],
                    'order_id'=>$credit['orderNum'],
                    'desc'=>$credit['description'],
                    'body'=>json_encode($credit),
                    'status'=>0,
                ]
            );
            $duiba->save();
            DB::table('user_score_item')->insert(['user_id'=>$userInfo->id, 'type'=>1, 'score'=>$credit['credits'], 'remark'=>'兑换商品']);
            if($userInfo->volunteer->score < 0 )
            {
                throw new \Exception('积分不足');
            }
            DB::commit();


        }catch (\Exception $e)
        {
            DB::rollBack();
            $userInfo = User::findorfail($userId);
            $data = [

                'status' => 'fail',
                'errorMessage' => $e->getMessage(),
                'credits' => $userInfo->volunteer->score,
            ];
            return $data;
        }

        $data = [

            'status' => 'ok',
            'errorMessage' => '',
            'bizId'=>$duiba->id,
            'credits' => $userInfo->volunteer->score,
        ];
        return $data;
    }

    public function notify(Request $request)
    {
        $orderId = $request->get('orderNum');

        $duiba = DuiBa::where('order_id', $orderId)->first();

        $userInfo = User::findorfail($duiba->user_id);
        $orgInfo = Org::where('id', $userInfo->org_id)->first();

        if($orgInfo->duiba_key != $request->get('appKey'))
        {
            $data = [

                'status' => 'fail',
                'errorMessage' => '用户信息错误，请联系管理员',
                'credits' => $userInfo->volunteer->score,
            ];
            return $data;
        }

        try{
            $credit = parseCreditNotify($orgInfo->duiba_key, $orgInfo->duiba_secret, $request->input());
        }catch (\Exception $e)
        {
            $data = [

                'status' => 'fail',
                'errorMessage' => $e->getMessage(),
                'credits' => $userInfo->volunteer->score,
            ];
            return $data;
        }

        if($request->get('success') == 'true')
        {
            $duiba->status = 1;
            $duiba->notify_body = json_encode($credit);
            $duiba->save();

            return 'ok';
        }else{
            if($duiba->status == 0)
            {
                $duiba->status = 2;
                $duiba->notify_body = json_encode($credit);
                $duiba->save();

                $userInfo->volunteer->increment('score', $duiba->score);
                DB::table('user_score_item')->insert(['user_id'=>$userInfo->id, 'type'=>0, 'score'=> $duiba->score, 'remark'=>'积分退回']);

                return 'ok';
            }

        }
    }

}
